package com.example.springboot0507.api.entity;

import cn.hutool.core.map.MapUtil;
import com.example.springboot0507.exception.ServiceException;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.net.URI;
import java.util.Map;

/**
 * @author 王博
 */
@SpringBootTest
public class EntityApi {
    @Resource
    private RestTemplate restTemplate;
    public void getEntity1(Long id,String name) {
        String url = "http://localhost:8080/entity/{id}?name={name}";
        ResponseEntity<User> response = restTemplate.getForEntity(url, User.class, id, name);
        HttpStatus statusCode = response.getStatusCode();
        if (!statusCode.is2xxSuccessful()) {
            throw new ServiceException("获取用户信息异常");
        }
        User body = response.getBody();
        System.out.println(body);
    }

    public void getEntity2(Long id, String name) {
        String url = "http://localhost:8080/entity/{id}?name={name}";
        Map<Object, Object> param = MapUtil.builder().put("id", id).put("name",name).build();
        ResponseEntity<User> response = restTemplate.getForEntity(url, User.class, param);
        HttpStatus statusCode = response.getStatusCode();
        if (!statusCode.is2xxSuccessful()) {
            throw new ServiceException("获取用户信息异常");
        }
        User body = response.getBody();
        System.out.println(body);
    }

    @Test
    public void getEntity3() {
        String url = "http://localhost:8080/entity/{id}";
        URI uri = UriComponentsBuilder.fromHttpUrl(url)
                .queryParam("name", "王博")
                .build()
                .expand(1)
                .toUri();
        ResponseEntity<User> response = restTemplate.getForEntity(uri, User.class);
        HttpStatus statusCode = response.getStatusCode();
        if (!statusCode.is2xxSuccessful()) {
            throw new ServiceException("获取用户信息异常");
        }
        User body = response.getBody();
        System.out.println(body);
    }
}
